import { NestInterceptor, Injectable, ExecutionContext, CallHandler } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { Observable, map } from 'rxjs';
import { ReturnType } from 'src/types';

/** 全局响应拦截器 */
@Injectable()
export class TransformerInterceptor implements NestInterceptor {
  constructor(private reflector: Reflector) {}

  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
    const returnType = this.reflector.get<ReturnType>('returnType', context.getHandler());
    const request = context.getArgByIndex(1).req as Request;
    return next.handle().pipe(
      map((data) => {
        switch (returnType) {
          case 'primitive':
            return data;
          default:
            return {
              code: 200,
              success: true,
              message: 'OK',
              data,
              originalUrl: request.originalUrl,
            };
        }
      }),
    );
  }
}
